package cn.zjj.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.zjj.domain.Product;
import cn.zjj.domain.Store;
import cn.zjj.feignClient.StoreFeignService;
import cn.zjj.mapper.ProductMapper;
import cn.zjj.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class ProductServiceImpl implements IProductService {
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private StoreFeignService storeFeignService;
    @Transactional
    @Override
    public Map<String,Object> insert(Product product) {
        if(StrUtil.isBlankIfStr(product)){
            Map<String,Object> exceptionMap=new HashMap<>();
            exceptionMap.put("success",false);
            exceptionMap.put("message","数据为空");
            return exceptionMap;
        }
        Product dbproduct = productMapper.selectByName(product);
        if(StrUtil.isBlankIfStr(dbproduct)){
            productMapper.insert(product);
            Store store = new Store();
            store.setProduct_id(product.getId());
            store.setNumber(product.getNumber());
            Map<String, Object> add = storeFeignService.add(store);
            if(add.get("success").equals(false)){
                productMapper.delete(product.getId());
            }
            return add;
        }
        Store dbstore = storeFeignService.selectById(dbproduct.getId());
        if(StrUtil.isBlankIfStr(dbstore)){
            Map<String,Object> exceptionMap=new HashMap<>();
            exceptionMap.put("success",false);
            exceptionMap.put("message","数据为空");
            return exceptionMap;
        }
        dbproduct.setPrice(product.getPrice());
        productMapper.update(dbproduct);//更新价格
        dbstore.setNumber(product.getNumber()+dbstore.getNumber());

        return storeFeignService.update(dbstore);
    }
}
